package de.karlNet.sambamanager.view.beans.forms;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.context.annotation.ScopedProxyMode;
import org.springframework.stereotype.Controller;

import de.karlNet.sambamanager.ldapController.commands.macros.CreateGroupMacro;
import de.karlNet.sambamanager.ldapModel.LdapGroup;
import de.karlNet.sambamanager.ldapModel.dto.LdapGroupCreationDTO;
import de.karlNet.sambamanager.view.beans.ManualLeafHandlingTreeNode;
import de.karlNet.sambamanager.view.beans.trees.LdapGroupBean;
import de.karlNet.sambamanager.view.beans.trees.LdapUserBean;
import de.karlNet.sambamanager.view.beans.trees.SelectedNodeContainer;

@Controller
@Scope(value = "session", proxyMode = ScopedProxyMode.TARGET_CLASS)
public class CreateGroupBean extends ViewBean {
	@Autowired
	protected SelectableGroupTree groupTree;

	@Autowired
	protected SelectableUserGroupTree selectableUserGroupTree;

	@Autowired
	private CreateGroupMacro createGroupMacro;

	@Autowired
	protected SelectedNodeContainer nodeContainer;

	@Autowired
	private LdapGroupBean ldapGroupBean;

	@Autowired
	private LdapUserBean ldapUserBean;

	protected LdapGroupCreationDTO ldapGroupCreationDTO = new LdapGroupCreationDTO();

	public LdapGroupCreationDTO getLdapGroupCreationDTO() {
		return ldapGroupCreationDTO;
	}

	public String create() {
		try {
			this.ldapGroupCreationDTO.getLdapGroup().setDn(
					"cn="
							+ this.ldapGroupCreationDTO.getLdapGroup().getCn()
							+ ","
							+ this.nodeContainer.selectedNode.getLdapObject()
									.getDn());

			this.ldapGroupCreationDTO.getMemberOf().addAll(
					this.groupTree.getSelectedGroups());
			this.ldapGroupCreationDTO.getMembers().addAll(
					this.selectableUserGroupTree.getSelectedUserGroups());
			this.createGroupMacro.createGroup(ldapGroupCreationDTO);
			if (this.nodeContainer.selectedNode.isExpanded()) {
				new ManualLeafHandlingTreeNode("group",
						this.ldapGroupCreationDTO.getLdapGroup(),
						this.nodeContainer.selectedNode);
			}
			this.ldapGroupCreationDTO = new LdapGroupCreationDTO();
			this.setShow(false);
			this.ldapGroupBean.reset();
			this.ldapUserBean.reset();
			return "index.html";
		} catch (Exception e) {
			this.showErrorMessage(e);
			return "";
		}
		
	}

	public LdapGroup getLdapGroup() {
		return this.ldapGroupCreationDTO.getLdapGroup();
	}

	@Override
	public String getPageName() {
		return "createGroupView";
	}
}
